<template>
  <div
    :id="id"
    :class="className"
    :style="{ height, width }"
    @click="showInfo"
  />
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted } from "vue";
import { init, type EChartsOption, type EChartsType } from "echarts";
import * as echarts from "echarts";
import type { SunnyProject } from "@/types/sunnyProject/type";
import { useChartStore } from "@/stores/chartStore";

const chartStore = useChartStore();
//定义一个普通变量作为成员变量，方便各个方法调用。
let chart: EChartsType;

onMounted(() => {
  //防止div还没加载的时候就开始去进行chart的初始化，等到vue完成一个tick的HTML元素更新之后再进行操作。
  nextTick(() => {
    initChart();
  }).then(() => {
    if (chart) chartStore.listenResize(chart);
  });
});

/**
 * 完成事件的解绑
 */
onUnmounted(() => {
  if (chart) chartStore.removeListener(chart);
});

const props = defineProps({
  id: {
    type: String,
    default: "ProBarChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
  title: {
    type: String,
  },
  chartData: { type: Array<SunnyProject>, required: true },
});

function initChart() {
  chart = init(document.getElementById(props.id) as HTMLDivElement);
  console.log("传入图表的数据是", props.chartData);

  chart.setOption({
    title: {
      show: true,
      text: props.title,
      x: "center",
      padding: 15,
      textStyle: {
        fontSize: 18,
        fontStyle: "normal",
        fontWeight: "bold",
        color: "#337ecc",
      },
    },
    grid: {
      show: false,
      left: "2%",
      right: "2%",
      bottom: "10%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999",
        },
      },
    },
    legend: {
      x: "center",
      y: "bottom",
      data: ["用例数", "模块数"],
    },
    xAxis: [
      {
        type: "category",
        data: props.chartData?.map((line) => line.name),
        axisPointer: {
          type: "shadow",
        },
        axisLabel: {
          padding: 0,
          overflow: "truncate",
          //强制显示所有x轴取值
          interval: 0,
        },
      },
    ],
    yAxis: [
      {
        name: "用例数（条）",
        type: "value",
        min: 0,
        max: Math.max.apply(
          Math,
          props.chartData.map((line) => line.caseCount)
        ),
        axisLabel: {
          formatter: "{value} ",
        },
      },
      {
        name: "模块数（个）",
        type: "value",
        min: 0,
        interval: 1,
        max: Math.max.apply(
          Math,
          props.chartData.map((line) =>
            line.moduleList?.length > 0 ? line.moduleList.split(",").length : 0
          )
        ),
        axisLabel: {
          formatter: "{value}",
        },
      },
    ],
    series: [
      {
        name: "用例数",
        type: "bar",
        data: props.chartData.map((line) => line.caseCount),
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
      },
      {
        name: "模块数",
        type: "bar",
        data: props.chartData.map((line) =>
          //注意这个?不能丢，加了？才能在moduleList为null的时候转为0
          line.moduleList?.length > 0 ? line.moduleList.split(",").length : 0
        ),
        barWidth: 20,
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#25d73c" },
            { offset: 0.5, color: "#1bc23d" },
            { offset: 1, color: "#179e61" },
          ]),
        },
      },
    ],
  } as EChartsOption);
}

function showInfo() {
  console.log("项目图表内的数据是", props.chartData);
}
</script>
